package fr.insee.solr.service.state;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.NestedNullException;
import org.apache.commons.beanutils.PropertyUtils;

import fr.insee.solr.model.annotation.SolrField;
import fr.insee.solr.service.impl.SolrInseeException;
import fr.insee.solr.utils.ReflectUtils;

public class StateNested implements IState{

	@Override
	public Object getValue(Field f, SolrField a, Object o) throws SolrInseeException {
		try {
			return PropertyUtils.getProperty(o, a.beanName());
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			throw new SolrInseeException(ERROR_NO_SUCH_FIELD + a.fieldName(),e);
		} catch (NestedNullException e){
			return null;
		}
	}

	@Override
	public void fillValue(Object bean, Field f, SolrField a, Object solrValue) throws SolrInseeException{
		try {
			ReflectUtils.instanciateAttributs(a.beanName(), bean);
			Class<?> type = PropertyUtils.getPropertyType(bean, a.beanName());
			Object value = ConvertUtils.convert(solrValue, type);
			PropertyUtils.setProperty(bean, a.beanName(), value);
		} catch (IllegalAccessException | InvocationTargetException	| NoSuchMethodException | InstantiationException e) {
			throw new SolrInseeException(ERROR_FILL_FIELD + a.fieldName()+" avec "+solrValue,e);
		}
	}






}
